package ktvdownloadserver

import (
	//	"bytes"
	"encoding/binary"
	"ktvserver/core/session"
	"ktvserver/core/tcpserver"
	"ktvserver/ktvutil"
	"log"
	"net"
)

// 下载服务器获取文件数据
const KTV_MAX_DOWNLOAD_SONG_IP_COUNT = (40)

// 下载服务器地址分配
type DownloadSongIpList struct {
	cbStructSize uint32                                 // 结构体大小 = sizeof(DownloadSongIpList)
	SongNum      uint32                                 // 歌曲编号
	Count        uint32                                 // 当前服务器的个数
	IP           [KTV_MAX_DOWNLOAD_SONG_IP_COUNT]uint32 //  IP地址列表
	Port         [KTV_MAX_DOWNLOAD_SONG_IP_COUNT]uint16 // 端口号
	Disk         [KTV_MAX_DOWNLOAD_SONG_IP_COUNT]byte   // 每个服务器上面对应的盘符

}

// 返回结构体大小
func (d *DownloadSongIpList) StructSize() int {
	return (4*3 + KTV_MAX_DOWNLOAD_SONG_IP_COUNT*(4+2+1))
}

// 清空所有的数据
func (d *DownloadSongIpList) Reset() {

	d.cbStructSize = uint32(d.StructSize())
	d.SongNum = 0
	d.Count = 0

	for i := 0; i < KTV_MAX_DOWNLOAD_SONG_IP_COUNT; i++ {
		d.IP[i] = 0
		d.Port[i] = 0
		d.Disk[i] = 0
	}

}

// REQUEST_DOWNLOAD_SONG_IP_LIST
func KtvDownloadSongIpList(w tcpserver.ResponseWriter, req *tcpserver.Request) {

	ktvinfo := tcpserver.GetKtvRequestInfo(req.DataBody)

	// 从filename位置复制8字节出来
	//tokenData := ktvinfo.FileName[0:4]

	// 检查下载的session是否有效
	//var token uint64
	//buf := new(bytes.Buffer)
	//binary.Write(buf, binary.LittleEndian, ktvinfo.FileName[0:4])
	//binary.Read(buf, binary.LittleEndian, &token)
	token := uint64(ktvinfo.FastForward) | uint64(ktvinfo.FFLength)<<32

	/*
		if session.IsAllow(token) != true {
			//	log.Printf("Invalid token")
			log.Printf("(%v) GetDownloadSongIP, invalid token, number=%d", req.RemoteIP(), ktvinfo.Number)
			tcpserver.WriteHeader(w, 0, session.KTV_SESSION_STATUS_INVALID)
			tcpserver.WriteFooter(w)
			return
		}
	*/

	// 记录到下载列表
	session.LogDownloadSongNum(token, ktvinfo.Number)
	req.SetToken(token)

	// 统计下载次数
	ktvutil.IncDonwloadSongCount()

	/// 返回下载地址

	var ipinfo DownloadSongIpList

	ipinfo.cbStructSize = uint32(ipinfo.StructSize())
	ipinfo.SongNum = ktvinfo.Number
	ipinfo.Count = 1
	ipinfo.Port[0] = uint16(ktvutil.GetDownloadServerPort())
	// 默认127.0.0.1
	ipinfo.IP[0] = uint32(127)<<24 | uint32(0)<<16 | uint32(0)<<8 | uint32(1)

	// 本地连接的地址
	localip := net.ParseIP(req.LocalIP()).To4()
	//log.Printf("localip=%s, v=%v", req.LocalIP(), localip)
	if localip != nil {
		ipinfo.IP[0] = uint32(localip[0])<<24 | uint32(localip[1])<<16 | uint32(localip[2])<<8 | uint32(localip[3])
	}

	// 打印显示信息
	log.Printf("(%v) GetDownloadSongIP, number=%d, ip=%v:%d",
		req.RemoteIP(),
		ktvinfo.Number,
		localip,
		ipinfo.Port[0])

	tcpserver.WriteHeader(w, uint32(ipinfo.StructSize()), 0)
	binary.Write(w, binary.LittleEndian, &ipinfo)
	tcpserver.WriteFooter(w)
}
